import React from 'react';
import { Form, Divider, Spin, Button } from 'antd';
import { connect } from 'umi';
// import { isMoment } from 'moment';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import { BottomAction } from '@/components';
// import pageTabUtil from '@/utils/pageTabUtil';
// import { addBackgroundRec } from '../service';
import { dictionaryList } from '@/services/dictionary';
import emptyImg from '@/assets/empty.png';
import cn from 'classnames';
import { TalentInfoHead } from '../../components';
import { getCandidateInfo } from '../../service';
import { getBgCompanyList } from '../service';
// import { WithDynamicKey } from '../containers';
import useGetBgRec from '../hooks/useGetBgRec';
// import BackgroundForm from './BackgroundForm';
import EditableDetailForm from './EditableDetailForm';
import styles from './index.less';

const BackgroundRec = ({ location = {} }) => {
    const { query = {} } = location;
    const { candidateId, employId } = query;
    const [showNewForm, setShowNewForm] = React.useState(false);
    const [count, setCount] = React.useState(1);
    const [showCover, setShowCover] = React.useState(true);
    const [loadingRec, recordList] = useGetBgRec({
        employId,
        count,
        onData: list => {
            if (list?.length === 0) {
                setShowNewForm(true);
            }
        }
    });

    const { data: talentInfo, run: fetchTalentDetail } = useRequest(() => getCandidateInfo(candidateId), {
        manual: true,
        initialData: {},
        ...defaultFormatResult
    });

    const { data: relateTypeList = [] } = useRequest(() => dictionaryList({ codes: ['backgroundRelateType'] }), {
        ...defaultFormatResult
    });

    const { data: bgCompanyList } = useRequest(() => getBgCompanyList(employId), {
        ...defaultFormatResult
    });

    // const resolveValues = data => {
    //     const allFieldsArr = Object.keys(data);
    //     const resolveResult = [];
    //     const allKeys = (() => {
    //         const result = [];
    //         allFieldsArr.forEach(field => {
    //             result.push(field.split('-')[1]);
    //         });
    //         return [...new Set(result)];
    //     })();
    //     allKeys.forEach(key => {
    //         const oneFormValues = { employId: Number(employId), candidateId: Number(candidateId) };
    //         // 找到所有的数据
    //         allFieldsArr.forEach(field => {
    //             if (field.split('-')[1] === key) {
    //                 oneFormValues[field.split('-')[0]] = isMoment(data[field])
    //                     ? data[field].format('YYYY-MM-DD HH:mm:00')
    //                     : data[field];
    //             }
    //         });
    //         resolveResult.push(oneFormValues);
    //     });
    //     return resolveResult;
    // };

    // const handleSubmit = e => {
    //     e.preventDefault();
    //     form.validateFieldsAndScroll(async (err, values) => {
    //         if (!err) {
    //             const result = resolveValues(values);
    //             setLoading(true);
    //             const response = await addBackgroundRec(result);
    //             setLoading(false);
    //             if (response.code === 10000) {
    //                 message.success('提交成功！');
    //                 setCount(count + 1);
    //             } else {
    //                 message.error(response.msg || '提交失败！');
    //             }
    //         }
    //     });
    // };

    React.useEffect(() => {
        fetchTalentDetail();
    }, []);

    const formItemLayout = {
        labelCol: {
            md: { span: 6 },
            xs: { span: 24 },
            sm: { span: 24 }
        },
        wrapperCol: {
            md: { span: 18 },
            xs: { span: 24 },
            sm: { span: 24 }
        }
    };

    const addBackRec = () => {
        setShowNewForm(true);
    };

    const renderContent = () => {
        if (loadingRec) {
            return <div />;
        }
        if (!recordList.length && showCover) {
            return (
                <div className={styles.empty}>
                    <img alt="" src={emptyImg} />
                    <h4>暂无背调记录</h4>
                    <p>候选人暂未提供背调人联系信息</p>
                    <Button type="primary" icon="plus" onClick={() => setShowCover(false)}>
                        添加背调
                    </Button>
                </div>
            );
        }

        const commonProps = {
            setCount,
            recordList,
            bgCompanyList,
            relateTypeList,
            formItemLayout,
            count,
            candidateId
        };

        return (
            <>
                <div
                    className={cn(styles.addBackRec, showNewForm ? styles.disabled : styles.active)}
                    onClick={addBackRec}
                >
                    + 添加背调记录
                </div>
                {showNewForm && (
                    <EditableDetailForm
                        employId={employId}
                        key="newForm"
                        index={recordList.length}
                        onSave={() => {
                            setShowNewForm(false);
                        }}
                        isAddForm
                        setShowNewForm={setShowNewForm}
                        {...commonProps}
                    />
                )}
                {recordList.length > 0 &&
                    recordList
                        .map((item, index) => (
                            <EditableDetailForm
                                isAddForm={false}
                                data={item}
                                index={index}
                                isDetailItem
                                {...commonProps}
                            />
                        ))
                        .reverse()}
            </>
        );
    };

    return (
        <PageHeaderWrapper>
            <div className={styles.bgRecWrap}>
                <TalentInfoHead talent={talentInfo || {}} />
                <Divider style={{ backgroundColor: '#ededed' }} />
                <Spin spinning={loadingRec}>{renderContent()}</Spin>
            </div>
        </PageHeaderWrapper>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create({})(BackgroundRec));
